<template>
  <section>
    <!--工具条 高级 查询位置-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <el-input v-model="filters.name" placeholder="姓名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-perm="'dept:get'" v-on:click="deptQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-perm="'dept:put'" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表
        :data="department":  绑定的数据
        highlight-current-row： 高亮显示
        v-loading="listLoading"：忙等框
        @selection-change="selsChange"：勾选复选框触发事件
        sortable： 排序
    -->
    <el-table :data="departments" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="部门名称" width="120" sortable>
      </el-table-column>
      <el-table-column prop="sn" label="部门编号" width="120" sortable>
      </el-table-column>
      <el-table-column prop="manager.username" label="部门领导" width="120" sortable>
      </el-table-column>
      <el-table-column prop="parent.name" label="上级部门" width="120" sortable>
      </el-table-column>

      <el-table-column prop="state" label="是否启用" width="100" sortable>
       <template scope="scope">
          <span style="color: green" v-if="scope.row.state==1" size="small" >启用</span>
          <span style="color: red" v-else-if="scope.row.state==0" size="small" >禁用</span>
          <span style="color: gray" v-else size="small">未知</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="150">
        <template scope="scope">
          <el-button size="small" v-perm="'dept:put'" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger"  v-perm="'dept:delete'" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" v-perm="'dept:patch'" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination
          layout="prev, pager, next"
          @current-change="handleCurrentChange"
          :page-size="pageSize"
          :total="totals"
          style="float:right;">
      </el-pagination>
    </el-col>

    <!--编辑界面-->
    <el-dialog :title="title" :visible.sync="editFormVisible" :close-on-click-modal="false">
      <el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="editForm.name" auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item label="部门编号" prop="sn">
          <el-input v-model="editForm.sn" auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item label="部门状态">
          <el-radio-group v-model="editForm.state">
            <el-radio class="radio" :label="1">启用</el-radio>
            <el-radio class="radio" :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="上级部门" prop="parent_id">
          <!--<el-input v-model="editForm.parent_id" auto-complete="off"></el-input>-->
          <el-cascader v-model="editForm.parent_id"
                       :options="tree"
                       :props="{
                checkStrictly: true,
                label:'name',
                value: 'id'
              }"
                       clearable>
          </el-cascader>
        </el-form-item>

        <el-form-item label="部门经理" prop="manager_id">
          <!-- <el-input v-model="editForm.manager_id" auto-complete="off"></el-input>-->、
          <!--
            v-for="item in cities":  循环
             :label:  展示的名字
             :value: 向后端传的值
          -->
          <el-select clearable v-model="editForm.manager_id" placeholder="请选择">
            <el-option
                v-for="item in employees"
                :label="item.username"
                :value="item.id">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
            </el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="editFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>


  </section>
</template>



<script>

	export default {
		data() {
			return {
        // 级联数据集合
        options: [],
        tree:[],
        // 高级查询字段集合
				filters: {
					name: ''
				},
				departments: [],
        employees: [],
				totals: 0,
        currentPage: 1,
        pageSize: 5,
        // 忙等框
				listLoading: false,
				sels: [],// 批量删除,列表选中列
        title: "",
				editFormVisible: false, // 编辑界面是否显示
				editLoading: false,
        // 模态框为空校验
				editFormRules: {
					name: [
						{ required: true, message: '请输入部门名称', trigger: 'blur' }
					],
          sn: [
            { required: true, message: '请输入部门编号', trigger: 'blur' }
          ]
				},
				//编辑界面数据
				editForm: {
          id: null,
          sn: '',
          name: '',
          state: null,
          manager_id: null,
          parent_id: null
				},
        cities: []
			}
		},
		methods: {

      getDepartmentTree(){
        this.$http.get("/dept/tree")
        .then(result=>{
          this.options = result.data;
        })
      },
      // 获取员工列表
      getEmployees() {
        this.$http.get("/emp")
          .then(result=>{
            this.cities = result.data;
          })
      },
      // 高级查询请求
      deptQuery(){
        // 查询完后跳转回第一页
        this.currentPage = 1;
        this.getDepartments();
      },
      // 当前页请求
			handleCurrentChange(currentPage) {
				this.currentPage = currentPage;
        // 从新加载分页内容
				this.getDepartments();
			},
			//获取部门列表
			getDepartments() {
				let para = {
          currentPage: this.currentPage,
          pageSize: this.pageSize,
          keywords: this.filters.name // 高级查询
				};
        // 开启忙等框
				this.listLoading = true;
			  // 发送axios请求
        this.$http.post("/dept", para)
        .then(result=>{
          this.departments = result.data.rows;
          this.totals = result.data.totals;
          // 关闭忙等框
          this.listLoading = false;
        }).catch(result=>{
          this.$message.error("系统繁忙,请稍后重试");
        })
			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
          // 开启忙等
					this.listLoading = true;
          // 发送axios请求
          this.$http.delete("/dept/" + row.id)
            .then(result=>{
            // 关闭忙等
            this.listLoading = false;
            if(result.data.success){
            this.$message({
              message: result.data.message,
              type: 'success'
            });
            }else {
              this.$message({
                message: result.data.message,
                type: 'error'
              });
            }
            // 删除后刷新页码
              this.currentPage = 1;
              this.getDepartments();
            })
              .catch(result=>{
                this.listLoading = false;
                this.$message({
                  message: '系统繁忙，请重试！',
                  type: 'error'
                });
          })
				}).catch(() => {
				});
			},

			//显示编辑界面
			handleEdit: function (index, row) {
        this.getDepartmentTree();
        this.title = "编辑";
        // 弹出编辑框
				this.editFormVisible = true;
        // 获取当前行对面克隆操作
				this.editForm = Object.assign({}, row);
        let arr = this.editForm.dirPath.split("/");
        let echoArr = [];
        for(var i = 1; i < arr.length - 1; i++) {
          echoArr.push(parseInt(arr[i]));
        }
        this.editForm.parent_id = echoArr;
			},
			//显示新增界面
			handleAdd: function () {
        this.getDepartmentTree();
        this.title = "新增";
				this.editFormVisible = true;
				this.editForm = {
          id: null,
          sn: '',
          name: '',
          state: null,
          manager_id: null,
          parent_id: null

        };
			},
			//编辑
			editSubmit: function () {
				this.$refs.editForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
              // 开启按钮忙等
							this.editLoading = true;
							//NProgress.start();
							let para = Object.assign({}, this.editForm);
              let arr = para.parent_id
              if (arr && arr.length == 0) {
                para.parent_id = null;
              }
              if (arr && arr.length > 0) {
                para.parent_id = arr[arr.length - 1];
              }
              // 效验格式,用不上
							// para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
              // 4.发送Axios请求
              this.$http.put("/dept", para)
                  .then(result=>{
                    // 1.关闭按钮忙等
                    this.editLoading = false;
                    // 2.关闭模态框
                    this.editFormVisible = false;
                    if(result.data.success){ // 新增/修改成功
                      this.$message({
                        message: result.data.message,
                        type: 'success'
                      });
                    }else { // 不一定新增/修改成功，我们也不知道新增/修改成功没有
                      this.$message({
                        message: result.data.message,
                        type: 'error'
                      });
                    }
                    // 3.改变当前页页码
                    // this.currentPage = 1;
                    // 4.调用查询列表函数
                    this.getDepartments();
                  })
                  .catch(result=>{
                    this.editLoading = false;
                    this.$message({
                      message: '系统繁忙，请重试！',
                      type: 'error'
                    });
                  })
						});
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
        // 获取选中id
				var ids = this.sels.map(item => item.id);
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
          this.$http.patch("/dept", ids)
              .then(result=>{
                // 关闭忙等
                this.listLoading = false;
                if(result.data.success){
                  this.$message({
                    message: result.data.message,
                    type: 'success'
                  });
                }else {
                  this.$message({
                    message: result.data.message,
                    type: 'error'
                  });
                }
                // 删除后刷新页码
                this.currentPage = 1;
                this.getDepartments();
              })
              .catch(result=>{
                this.listLoading = false;
                this.$message({
                  message: '系统繁忙，请重试！',
                  type: 'error'
                });
              })
				}).catch(() => {

				});
			}
		},
		mounted() {
      // 获取部门列表数据
      this.getDepartments();
      // 获取员工列表数据
      this.getEmployees();
      // 部门树集合数据
      this.getDepartmentTree();
		}
	}

</script>

<style scoped>

</style>